package com.idev.common.util;

import lombok.Data;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;

/**
 * Created by yigeyanse on 2017/6/21.
 */

@Data
@Component
public class ThymeLeafTemplateMail {
    private static final Logger logger = Logger.getLogger(ThymeLeafTemplateMail.class);

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;

    private String from;
    private String toEmail;
    private String subject;
    private Context model;
    private String templateName;

    public void sendEmail() throws Exception {
        final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setTo(toEmail);
        message.setFrom(from);
        String str = getMessage();
        //页面中不允许&单独存在，不然直接就报异常，当编译过后再进行删除
        String str1=str.replaceAll("<!\\[CDATA\\[", "");
        String messages=str1.replaceAll("]]>", "");
        System.out.println(messages);
        message.setText(messages,true);//此处设置为true发送为html,false为文本,默认为 false
        javaMailSender.send(mimeMessage);
    }

    /**
     *把html页面编译为String
     */
    public String getMessage() {
        //传入页面地址，与参数
        return templateEngine.process(templateName, model);
    }

}
